home *** CD-ROM | disk | FTP | other *** search
- /* dup2.c --- p 494 */
- #include <stdio.h>
- #include <io.h>
- main()
- {
- int saved_handle;
- char filename[81];
- FILE *new_stdout;
- /* Ask for filename to which stdout will be assigned */
- printf("Enter filename to which stdout will be assigned:");
- gets(filename);
- if((new_stdout = fopen(filename, "w")) == NULL)
- {
- perror("fopen failed");
- exit(1);
- }
- /* First duplicate the handle for stdout so that we can
- * reset things at the end */
- if((saved_handle = dup(1)) == -1)
- {
- perror("dup failed on handle 1!");
- exit(1);
- }
- /* Get the handle of the new file using 'fileno' and
- * assign handle 1 (stdout) to it by calling dup2 */
- if(dup2(fileno(new_stdout), 1) == -1)
- perror("dup2 failed to assign handle 1!");
- else
- {
- printf("New handle for stdout is %d\n", fileno(new_stdout));
- printf("Testing dup2. This should be in file: %s\n",
- filename);
- /* flush to send output to open file */
- fflush(stdout);
- dup2(saved_handle, 1);
- printf("Enter 'TYPE %s' to see result\n", filename);
- }
- }